package com.piece.admin.service;

import com.piece.admin.model.OauthClientDetails;
import com.piece.admin.repository.OauthClientDetailsRepository;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.jpa.repository.BaseService;
import com.piece.core.authentication.service.CustomClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

@Service
@Transactional
public class OauthClientDetailsService extends BaseService<OauthClientDetails, String> {

    @Autowired
    private OauthClientDetailsRepository oauthClientDetailsRepository;

    @Resource
    private CustomClientDetailsService clientDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostConstruct
    public void initRepository() {
        setRepository(oauthClientDetailsRepository);
    }

    public OauthClientDetails insertOrUpdate(OauthClientDetails details, boolean insert) {
        // 设置密码
        if (StringUtil.isNotEmpty(details.getClientSecretStr())) {
            details.setClientSecret(passwordEncoder.encode(details.getClientSecretStr()));
        }

        if (insert) {
            details.setCreateTime(new Date());
            details.setUpdateTime(new Date());
            details = oauthClientDetailsRepository.insert(details);
        } else {
            details.setUpdateTime(new Date());
            oauthClientDetailsRepository.update(details);
        }

        clientDetailsService.cacheAndGetClient(details.getClientId());
        return details;
    }

    public void delete(String clientId) {
        oauthClientDetailsRepository.delete(clientId);
        clientDetailsService.removeClientDetails(clientId);
    }
}
